<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>图片模糊(均值模糊)</title>
		<style type="text/css">
			.scream{
				width:400px;
				height:300px;
				position: absolute;
				top:60px;
				border: 1px solid;
			}
			#canvas{
				position: absolute;
				top:60px;
				left:500px;
				border: 1px dashed;
			}
		</style>
	</head>
	<body>
		<input type="file" onchange="loadImg()"/>
		<input type="button" value="模糊化" onclick="Fuzzy()"/>
		<br/><br/>
		<div class="scream">
			<img id="scream" width="400px" height="300px" alt="Image preview...">
		</div>
		<canvas id="canvas" width="400px;" height="300px;">
		</canvas>
		
		<script>
			function Fuzzy(){
				 var c=document.getElementById("canvas");
			  var ctx=c.getContext("2d");
			  var imgData=ctx.getImageData(0,0,c.width,c.height);
			  var img_w = imgData.width;
			  var img_h = imgData.height;
			  
			  for(var w=1;w<(img_w-1);w++){
			   	for(var h=1;h<(img_h-1);h++){
			    		//起始点
			    		var i = (w+img_w*h)*4;
			    		var R = imgData.data[i-1604]+imgData.data[i-1600]+imgData.data[i-1596]+imgData.data[i-4]+imgData.data[i]
			    		+imgData.data[i+4]+imgData.data[i+1596]+imgData.data[i+1600]+imgData.data[i+1604];	//R(0-255)
				    	var G = imgData.data[i-1603]+imgData.data[i-1599]+imgData.data[i-1595]+imgData.data[i-3]+imgData.data[i+1]
			    		+imgData.data[i+5]+imgData.data[i+1597]+imgData.data[i+1601]+imgData.data[i+1605];	//G(0-255)
				    	var B = imgData.data[i-1602]+imgData.data[i-1598]+imgData.data[i-1594]+imgData.data[i-2]+imgData.data[i+2]
			    		+imgData.data[i+6]+imgData.data[i+1598]+imgData.data[i+1602]+imgData.data[i+1606];;	//G(0-255)
				    	var Alpha = imgData.data[i+3];	//Alpha(0-255)
		    	
				    	imgData.data[i] = R/9;
				        imgData.data[i+1] = G/9;	
				        imgData.data[i+2] = B/9;	
				        imgData.data[i+3] = Alpha;	
			    	}
			    }
			    ctx.putImageData(imgData,0,0);
			}
		</script>
		<script>
			//canvas图像的宽高 
			var c_w = 400; var c_h = 300;
			//加载img图像
			function loadImg(){
				var img = document.getElementById("scream");
				var file    = document.querySelector('input[type=file]').files[0];
				if(!/image\/\w+/.test(file.type)){
			        alert("文件必须为图片！");
			        return false;
			    }
				var reader  = new FileReader();
				reader.addEventListener("load", function () {
				    img.src = reader.result;
				}, false);
				
				if(file) {
					reader.readAsDataURL(file);
					loadCanvas();
				}
			}
			//加载canvas图像
			function loadCanvas(){
				var c=document.getElementById("canvas");
				var ctx=c.getContext("2d");
				
				var img = document.getElementById("scream");
				img.onload = function() {
					ctx.drawImage(img,0,0,c_w,c_h);
				} 
			}
		</script>
	</body>
</html>

